//订单详情 状态 99-全部 0-已取消 1-待付款 2-待发货 3-待收货 4-已关闭 5-已完成 88-待评价
const app = getApp();
const api = require("../../server/Api.js");
const payHelper = require("../../utils/pay.js")
const QR = require("../../utils/qrcode.js")
const util = require("../../utils/util.js");
Page({
  data: {
    showPayTypeDialog: false,
    showCancelDialog: false,
    status: 3,
    orderId: "",
    statusInfo: {
      0: {
        statusName: '订单已取消',
        statusDesc: '订单已取消，期待您的再次光临。',
        showAddress: true,
        btns: [{
          name: '再来一单',
          color: 'red'
        }]
      },
      1: {
        statusName: '订单待付款',
        statusDesc: '下单15分钟后将自动取消，请尽快付款。',
        showAddress: true,
        btns: [{
            name: '取消订单',
            color: 'gray'
          },
          {
            name: '立即付款',
            color: 'red'
          }
        ]
      },
      2: {
        statusName: '订单待配送',
        statusDesc: '商家正在准备商品中',
        btns: [
          {
            name: '再来一单',
            color: 'red'
          }
        ]
      },
      3: {
        statusName: '订单配送中',
        statusDesc: '订单配送中，请耐心等待。',
        btns: [
          {
            name: '再来一单',
            color: 'red'
          }
        ]
      },
      4: {
        //已完成
        statusName: '订单已送达',
        statusDesc: '感谢您对好获严选的信任，期待再次光临。',
        btns: [{
          name: '再来一单',
          color: 'red'
        }],
      },
      98: {
        //待自提
        statusName: '订单待提货',
        statusDesc: '请等待短信通知提货。',
        showAddress: true,
        btns: [ {
          name: '再来一单',
          color: 'red'
        }],
      },
      97: {
        //已自提
        statusName: '订单已提货',
        statusDesc: '感谢您对好获严选的信任，期待再次光临。',
        showAddress: true,
        hideBarCode: true,
        btns: [{
          name: '再来一单',
          color: 'red'
        }]
      },
      96: {
        statusName: '订单已关闭',
        statusDesc: '订单已关闭，期待您的再次光临。',
        btns: [{
          name: '再来一单',
          color: 'red'
        }]
      },
    },
    item: {},
    distance: "?km"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      })
    }

    this.queryOrderDetail();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  //查询订单详情
  queryOrderDetail: function() {
    let that = this;
    let orderId = this.data.orderId;
    app.showLoading();
    api.queryOrderDetail(orderId, 0, 0).then(res => {
      tt.hideLoading()
      res = util.formatOrderStatus(res);
      res.orderCnStatus = "订单" + res.orderCnStatus;
      if (res.orderStatus === 98 && res.payStatus === 1 && res.payTime && res.list && res.list.length > 0 && res.list[0].receiptInterval) {
        that.data.statusInfo[res.orderStatus].statusDesc = "商品预计" + app.getZtDate(res.deliveryTime) + "可提货，请等待短信通知"
        that.setData({
          statusInfo: that.data.statusInfo
        })
      }
      console.log(res);
      for (let i = 0; i < res.list.length; i++) {
        res.list[i].goodsImage = app.resetImageUrl(res.list[i].goodsImage, 172, 172)
      }
      res.store = {
        storeName: res.storeName,
        address: res.address
      }
      that.setData({
        item: res
      })
      if (that.data.statusInfo[that.data.item.orderStatus].showAddress) {
        app.globalData.qqmapsdk.calculateDistance({
          mode: "straight",
          to: res.storeLatitude + "," + res.storeLongitude,
          success: function(res) {
            if (res.result.elements.length > 0) {
              that.setData({
                distance: app.setMtoKm(res.result.elements[0].distance)
              })
            }
          },
          fail: function(error) {
            console.error("获取距离失败", error);
          },
        });
      }
      console.log(res);
      if ((res.shippingStatus == 3 || res.shippingStatus == 4) && res.code) {
        var size = this.setCanvasSize(); //动态设置画布大小 
        this.createQrCode(res.code, "mycanvas", size.w, size.h);
      }
    }).catch(msg => {
      tt.hideLoading()
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message)
    })
  },

  //适配不同屏幕大小的canvas
  setCanvasSize: function() {
    var size = {};
    try {
      var scale = 750 / 200;
      var width = app.globalData.windowWidth / scale;
      var height = width; //canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  /**
   * 绘制二维码图片
   */
  createQrCode: function(url, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    QR.api.draw(url, canvasId, cavW, cavH);
  },

  opertionTap: function(e) {
    let operName = e.currentTarget.id; //操作类型
    switch (operName) {
      case "取消订单":
        this.setData({
          operType: 1
        })
        this.showCancelDialog();
        break;
      case "删除订单":
        this.setData({
          operType: 2
        })
        this.showCancelDialog();
        break;
      case "立即付款":
        this.showPayTypeDialog();
        break;
      case "再来一单":
        tt.switchTab({
          url: '../index/index'
        })
        break
    }
  },

  //请求删除or取消订单
  onConfirm: function() {
    let that = this;
    let curOrder = this.data.item;
    let operType = this.data.operType;
    if (operType == 2) {
      app.showLoading()
      api.deleteOrder(curOrder.orderId).then(res => {
        tt.hideLoading()
        tt.showToast({
          title: '删除成功',
        })
        setTimeout(function() {
          tt.navigateBack({
            delta: 1,
          })
        }, 1000)
      }).catch(msg => {
        tt.hideLoading()
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    } else { //取消订单
      let promise = undefined
      if (curOrder.payStatus === 0) {
        promise = api.cancelOrder(curOrder.orderId)
      } else {
        promise = api.refundOrder(curOrder.orderId)
      }
      promise.then(res => {
        that.queryOrderDetail();
        tt.showToast({
          title: '取消成功',
        })
      }).catch(msg => {
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    }
  },

  //显示支付方式弹窗
  showPayTypeDialog: function() {
    this.setData({
      showPayTypeDialog: true,
    })
  },

  //显示是否弹出取消订单的操作
  showCancelDialog: function() {
    this.setData({
      showCancelDialog: true,
    })
  },
  //隐藏所有弹窗
  hiddenDialog: function(e) {
    this.setData({
      showPayTypeDialog: false,
      showCancelDialog: false
    })
    this.queryOrderDetail();
  },
  copyTxt: function(e) {
    app.copyTxt(e);
    return;
  },
  viewmap(e) {
    console.log(e);
    tt.openLocation({
      latitude: parseFloat(e.currentTarget.dataset.lat),
      longitude: parseFloat(e.currentTarget.dataset.lng),
      scale: 18
    })
  },
  tel() {
    if (this.data.item.storeTelephone) {
      app.makePhoneCall(this.data.item.storeTelephone)
    } else {
      app.showToast("商家电话未知")
    }
  }
})